#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
🎬 GIF背景去除工具 - 极致美化版
一键去除GIF图像的背景，使其透明
具有现代化UI和动态效果
"""

import os
import sys
from PIL import Image, ImageSequence
import numpy as np
from pathlib import Path
import argparse
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import threading
from collections import Counter
import time
import random

# 尝试导入scipy，如果没有则使用备用方案
try:
    from scipy import ndimage
    HAS_SCIPY = True
except ImportError:
    HAS_SCIPY = False
    print("⚠️ 警告: 未安装scipy，边框去除功能将使用备用算法")

# 美化用的颜色配置 - 扁平化现代风格
COLORS = {
    'primary': '#667eea',
    'primary_hover': '#5a67d8',
    'secondary': '#f093fb',
    'accent': '#4facfe',
    'success': '#48bb78',
    'warning': '#ed8936',
    'error': '#f56565',
    'background': '#f7fafc',
    'card': '#ffffff',
    'text': '#2d3748',
    'text_light': '#718096',
    'border': '#e2e8f0',
    'shadow': '#e2e8f0'
}

# 现代化按钮样式配置
BUTTON_STYLES = {
    'primary': {
        'bg': COLORS['primary'],
        'hover': COLORS['primary_hover'],
        'text': '#ffffff',
        'shadow': '#e2e8f0'
    },
    'secondary': {
        'bg': COLORS['secondary'],
        'hover': '#e879f9',
        'text': '#ffffff',
        'shadow': '#f0e6ff'
    },
    'success': {
        'bg': COLORS['success'],
        'hover': '#38a169',
        'text': '#ffffff',
        'shadow': '#e6f7ed'
    },
    'accent': {
        'bg': COLORS['accent'],
        'hover': '#3182ce',
        'text': '#ffffff',
        'shadow': '#e6f3ff'
    }
}

# 动态emoji图标集合
EMOJIS = {
    'gif': ['🎬', '🎥', '🎞️'],
    'magic': ['✨', '🪄', '⭐'],
    'process': ['⚙️', '🔄', '⚡'],
    'success': ['✅', '🎉', '💫'],
    'fire': ['🔥', '💥', '⚡']
}

class ModernButton(tk.Button):
    """现代化按钮组件"""
    def __init__(self, parent, style='primary', **kwargs):
        self.style_config = BUTTON_STYLES.get(style, BUTTON_STYLES['primary'])

        super().__init__(parent,
                        bg=self.style_config['bg'],
                        fg=self.style_config['text'],
                        relief='flat',
                        borderwidth=0,
                        font=('Microsoft YaHei UI', 10, 'bold'),
                        cursor='hand2',
                        **kwargs)

        self.bind('<Enter>', self.on_enter)
        self.bind('<Leave>', self.on_leave)
        self.bind('<Button-1>', self.on_click)

        # 添加阴影效果
        self.configure(highlightthickness=0)

    def on_enter(self, event):
        self.configure(bg=self.style_config['hover'])

    def on_leave(self, event):
        self.configure(bg=self.style_config['bg'])

    def on_click(self, event):
        # 点击动画效果
        self.configure(relief='solid', borderwidth=1)
        self.after(100, lambda: self.configure(relief='flat', borderwidth=0))

class AnimatedIcon:
    """动画图标类"""
    def __init__(self, icons, speed=2000):
        self.icons = icons
        self.speed = speed
        self.current_index = 0

    def get_current(self):
        return self.icons[self.current_index]

    def next(self):
        self.current_index = (self.current_index + 1) % len(self.icons)
        return self.get_current()

class GifBackgroundRemover:
    def __init__(self):
        self.supported_formats = ['.gif']

    def remove_background_by_color(self, gif_path, output_path=None, bg_color=None, tolerance=30, remove_border=True, border_expansion=3):
        """
        通过指定背景颜色去除背景

        Args:
            gif_path: 输入GIF文件路径
            output_path: 输出文件路径
            bg_color: 背景颜色 (R, G, B) 或 'auto' 自动检测
            tolerance: 颜色容差
            remove_border: 是否去除外边框
            border_expansion: 边框扩展像素数
        """
        try:
            # 打开GIF文件
            gif = Image.open(gif_path)

            if output_path is None:
                output_path = gif_path.replace('.gif', '_transparent.gif')

            frames = []

            for frame_index, frame in enumerate(ImageSequence.Iterator(gif)):
                # 转换为RGBA模式
                frame = frame.convert('RGBA')

                # 如果是第一帧且需要自动检测背景色
                if frame_index == 0 and (bg_color is None or bg_color == 'auto'):
                    bg_color = self._detect_background_color(frame)
                    print(f"检测到的背景色: RGB{bg_color}")

                # 去除背景
                frame_array = np.array(frame)

                if bg_color:
                    # 计算颜色差异
                    diff = np.abs(frame_array[:, :, :3].astype(int) - np.array(bg_color))
                    mask = np.all(diff <= tolerance, axis=2)

                    # 设置透明度
                    frame_array[mask, 3] = 0

                    # 去除外边框
                    if remove_border:
                        frame_array = self._remove_border(frame_array, bg_color, tolerance, border_expansion)

                # 转换回PIL Image
                processed_frame = Image.fromarray(frame_array, 'RGBA')
                frames.append(processed_frame)

            # 保存处理后的GIF
            if frames:
                frames[0].save(
                    output_path,
                    save_all=True,
                    append_images=frames[1:],
                    duration=gif.info.get('duration', 100),
                    loop=gif.info.get('loop', 0),
                    transparency=0,
                    disposal=2
                )

                print(f"成功保存透明背景GIF: {output_path}")
                return True

        except Exception as e:
            print(f"处理失败: {str(e)}")
            return False

    def _remove_border(self, frame_array, bg_color, tolerance, expansion=3):
        """
        去除外边框，处理边缘的半透明像素

        Args:
            frame_array: 图像数组
            bg_color: 背景色
            tolerance: 容差
            expansion: 边框扩展像素数
        """
        h, w = frame_array.shape[:2]

        # 创建一个掩码来标记需要去除的像素
        mask = np.zeros((h, w), dtype=bool)

        # 1. 标记与背景色相似的像素
        diff = np.abs(frame_array[:, :, :3].astype(int) - np.array(bg_color))
        bg_mask = np.all(diff <= tolerance, axis=2)
        mask |= bg_mask

        # 2. 扩展边框检测 - 处理渐变和半透明效果
        # 增加容差范围来捕捉边缘的过渡像素
        extended_tolerance = tolerance + 20
        diff_extended = np.abs(frame_array[:, :, :3].astype(int) - np.array(bg_color))
        extended_bg_mask = np.all(diff_extended <= extended_tolerance, axis=2)

        # 3. 边缘扩展算法
        for _ in range(expansion):
            if HAS_SCIPY:
                # 使用scipy的膨胀操作
                dilated = ndimage.binary_dilation(mask, structure=np.ones((3, 3)))
            else:
                # 备用的膨胀算法
                dilated = self._manual_dilation(mask)

            # 只在扩展的背景色相似区域中应用
            new_transparent = dilated & extended_bg_mask
            mask |= new_transparent

        # 4. 处理边缘的半透明像素
        # 对于边缘像素，根据与背景色的相似度调整透明度
        edge_pixels = self._find_edge_pixels(mask)

        for y, x in edge_pixels:
            if 0 <= y < h and 0 <= x < w:  # 边界检查
                pixel_color = frame_array[y, x, :3]
                color_diff = np.linalg.norm(pixel_color.astype(int) - np.array(bg_color))

                # 根据颜色差异计算新的透明度
                if color_diff <= tolerance * 2:
                    # 线性插值计算透明度
                    alpha_reduction = min(1.0, color_diff / (tolerance * 2))
                    new_alpha = int(frame_array[y, x, 3] * alpha_reduction)
                    frame_array[y, x, 3] = max(0, new_alpha)

        # 5. 应用最终的透明度
        frame_array[mask, 3] = 0

        return frame_array

    def _manual_dilation(self, mask):
        """
        手动实现膨胀操作（scipy的备用方案）
        """
        h, w = mask.shape
        dilated = mask.copy()

        # 3x3结构元素的膨胀
        for y in range(1, h-1):
            for x in range(1, w-1):
                if not mask[y, x]:  # 如果当前像素不在掩码中
                    # 检查周围3x3区域
                    if np.any(mask[y-1:y+2, x-1:x+2]):
                        dilated[y, x] = True

        return dilated

    def _find_edge_pixels(self, mask):
        """
        找到掩码边缘的像素点
        """
        if HAS_SCIPY:
            # 使用scipy的膨胀和腐蚀操作找到边缘
            dilated = ndimage.binary_dilation(mask, structure=np.ones((3, 3)))
            edge = dilated & ~mask
        else:
            # 备用的边缘检测算法
            edge = self._manual_edge_detection(mask)

        # 返回边缘像素的坐标
        edge_coords = np.where(edge)
        return list(zip(edge_coords[0], edge_coords[1]))

    def _manual_edge_detection(self, mask):
        """
        手动实现边缘检测（scipy的备用方案）
        """
        h, w = mask.shape
        edge = np.zeros_like(mask, dtype=bool)

        # 寻找掩码边缘：非掩码像素周围有掩码像素
        for y in range(1, h-1):
            for x in range(1, w-1):
                if not mask[y, x]:  # 如果当前像素不在掩码中
                    # 检查周围8个方向是否有掩码像素
                    neighbors = mask[y-1:y+2, x-1:x+2]
                    if np.any(neighbors):
                        edge[y, x] = True

        return edge

    def remove_background_edge_detection(self, gif_path, output_path=None, remove_border=True):
        """
        使用边缘检测方法去除背景
        """
        try:
            gif = Image.open(gif_path)

            if output_path is None:
                output_path = gif_path.replace('.gif', '_transparent_edge.gif')

            frames = []

            for frame in ImageSequence.Iterator(gif):
                frame = frame.convert('RGBA')
                frame_array = np.array(frame)

                # 简单的边缘检测背景去除
                # 假设边缘处的像素是前景，中心相似的大面积是背景
                gray = np.mean(frame_array[:, :, :3], axis=2)

                # 检测最常见的颜色作为背景
                flat_colors = [tuple(pixel) for pixel in frame_array[:, :, :3].reshape(-1, 3)]
                most_common_color = Counter(flat_colors).most_common(1)[0][0]

                # 去除最常见的颜色
                diff = np.abs(frame_array[:, :, :3].astype(int) - np.array(most_common_color))
                mask = np.all(diff <= 20, axis=2)
                frame_array[mask, 3] = 0

                # 去除外边框
                if remove_border:
                    frame_array = self._remove_border(frame_array, most_common_color, 20, 2)

                processed_frame = Image.fromarray(frame_array, 'RGBA')
                frames.append(processed_frame)

            if frames:
                frames[0].save(
                    output_path,
                    save_all=True,
                    append_images=frames[1:],
                    duration=gif.info.get('duration', 100),
                    loop=gif.info.get('loop', 0),
                    transparency=0,
                    disposal=2
                )

                print(f"成功保存透明背景GIF: {output_path}")
                return True

        except Exception as e:
            print(f"处理失败: {str(e)}")
            return False

    def _detect_background_color(self, frame):
        """
        自动检测背景颜色（通常是图像四角最常见的颜色）
        """
        frame_array = np.array(frame)
        h, w = frame_array.shape[:2]

        # 取四个角落的像素
        corners = [
            frame_array[0, 0, :3],  # 左上
            frame_array[0, w-1, :3],  # 右上
            frame_array[h-1, 0, :3],  # 左下
            frame_array[h-1, w-1, :3]  # 右下
        ]

        # 同时考虑边缘像素
        edge_pixels = []
        edge_pixels.extend(frame_array[0, :, :3])  # 上边
        edge_pixels.extend(frame_array[-1, :, :3])  # 下边
        edge_pixels.extend(frame_array[:, 0, :3])  # 左边
        edge_pixels.extend(frame_array[:, -1, :3])  # 右边

        # 统计最常见的颜色
        edge_colors = [tuple(pixel) for pixel in edge_pixels]
        most_common = Counter(edge_colors).most_common(1)

        if most_common:
            return most_common[0][0]
        else:
            return (255, 255, 255)  # 默认白色

    def batch_process(self, input_dir, output_dir=None, method='color', bg_color='auto', remove_border=True):
        """
        批量处理文件夹中的所有GIF文件
        """
        input_path = Path(input_dir)
        if output_dir:
            output_path = Path(output_dir)
            output_path.mkdir(exist_ok=True)
        else:
            output_path = input_path / 'transparent_output'
            output_path.mkdir(exist_ok=True)

        gif_files = []
        for ext in self.supported_formats:
            gif_files.extend(input_path.glob(f'*{ext}'))

        if not gif_files:
            print("未找到GIF文件")
            return

        print(f"找到 {len(gif_files)} 个GIF文件")

        success_count = 0
        for gif_file in gif_files:
            print(f"正在处理: {gif_file.name}")
            output_file = output_path / f"transparent_{gif_file.name}"

            if method == 'color':
                if self.remove_background_by_color(str(gif_file), str(output_file), bg_color, remove_border=remove_border):
                    success_count += 1
            elif method == 'edge':
                if self.remove_background_edge_detection(str(gif_file), str(output_file), remove_border=remove_border):
                    success_count += 1

        print(f"批量处理完成: {success_count}/{len(gif_files)} 个文件处理成功")


class GifBackgroundRemoverGUI:
    def __init__(self):
        self.remover = GifBackgroundRemover()
        self.animated_icons = {
            'title': AnimatedIcon(EMOJIS['gif']),
            'process': AnimatedIcon(EMOJIS['process'])
        }
        self.setup_gui()
        self.start_animations()

    def setup_gui(self):
        self.root = tk.Tk()
        self.root.title("🎬 GIF背景去除工具 - 现代化版")
        self.root.geometry("1200x700")
        self.root.resizable(True, True)
        self.root.configure(bg=COLORS['background'])

        # 设置应用图标
        try:
            self.root.iconbitmap(default='')
        except:
            pass

        # 创建主容器 - 横向布局
        self.create_main_layout()

        # 初始化变量
        self.initialize_variables()

    def create_main_layout(self):
        """创建现代化横向布局"""
        # 顶部标题栏
        self.create_header()

        # 主内容区域 - 横向三栏布局
        main_container = tk.Frame(self.root, bg=COLORS['background'])
        main_container.pack(fill='both', expand=True, padx=20, pady=(0, 20))

        # 左侧：文件选择和配置区域
        self.create_left_panel(main_container)

        # 中间：处理控制区域
        self.create_center_panel(main_container)

        # 右侧：日志显示区域
        self.create_right_panel(main_container)

    def create_header(self):
        """创建现代化头部"""
        header = tk.Frame(self.root, bg=COLORS['primary'], height=80)
        header.pack(fill='x')
        header.pack_propagate(False)

        # 标题容器
        title_container = tk.Frame(header, bg=COLORS['primary'])
        title_container.pack(expand=True, fill='both')

        # 动画标题
        self.title_label = tk.Label(title_container,
                                   text="🎬 GIF背景去除工具",
                                   bg=COLORS['primary'],
                                   fg='white',
                                   font=('Microsoft YaHei UI', 28, 'bold'))
        self.title_label.pack(expand=True)

        # 副标题
        subtitle = tk.Label(title_container,
                           text="✨ 现代化设计 • 一键去除背景 • 极致体验 ✨",
                           bg=COLORS['primary'],
                           fg='#e6f3ff',
                           font=('Microsoft YaHei UI', 12))
        subtitle.pack()

    def create_left_panel(self, parent):
        """创建左侧配置面板"""
        left_panel = tk.Frame(parent, bg=COLORS['card'], relief='flat', bd=0)
        left_panel.pack(side='left', fill='both', expand=True, padx=(0, 10))

        # 面板标题
        panel_title = tk.Label(left_panel, text="📁 文件 & 配置",
                              bg=COLORS['card'], fg=COLORS['text'],
                              font=('Microsoft YaHei UI', 16, 'bold'))
        panel_title.pack(pady=(20, 15))

        # 文件选择区域
        file_section = tk.Frame(left_panel, bg=COLORS['card'])
        file_section.pack(fill='x', padx=20, pady=(0, 20))

        # 文件选择按钮
        btn_frame = tk.Frame(file_section, bg=COLORS['card'])
        btn_frame.pack(fill='x', pady=(0, 15))

        self.single_file_btn = ModernButton(btn_frame, text="📄 选择单个文件",
                                          style='primary', command=self.select_single_file)
        self.single_file_btn.pack(fill='x', pady=(0, 8))

        self.batch_btn = ModernButton(btn_frame, text="📁 批量处理文件夹",
                                    style='secondary', command=self.select_folder)
        self.batch_btn.pack(fill='x')

        # 文件状态显示
        self.file_status = tk.Label(file_section, text="🔍 请选择文件或文件夹",
                                   bg=COLORS['card'], fg=COLORS['text_light'],
                                   font=('Microsoft YaHei UI', 10), wraplength=250)
        self.file_status.pack(pady=(10, 0))

        # 分隔线
        separator1 = tk.Frame(left_panel, bg=COLORS['border'], height=1)
        separator1.pack(fill='x', padx=20, pady=15)

        # 处理选项区域
        options_section = tk.Frame(left_panel, bg=COLORS['card'])
        options_section.pack(fill='x', padx=20)

        # 方法选择
        method_label = tk.Label(options_section, text="🔧 处理方法",
                               bg=COLORS['card'], fg=COLORS['text'],
                               font=('Microsoft YaHei UI', 12, 'bold'))
        method_label.pack(anchor='w', pady=(0, 8))

        self.method_var = tk.StringVar(value="color")
        method_frame = tk.Frame(options_section, bg=COLORS['card'])
        method_frame.pack(fill='x', pady=(0, 15))

        tk.Radiobutton(method_frame, text="🎨 颜色匹配", variable=self.method_var,
                      value="color", bg=COLORS['card'], fg=COLORS['text'],
                      font=('Microsoft YaHei UI', 10), selectcolor=COLORS['primary']).pack(anchor='w')
        tk.Radiobutton(method_frame, text="🔍 边缘检测", variable=self.method_var,
                      value="edge", bg=COLORS['card'], fg=COLORS['text'],
                      font=('Microsoft YaHei UI', 10), selectcolor=COLORS['primary']).pack(anchor='w')

        # 背景色设置
        color_label = tk.Label(options_section, text="🌈 背景色",
                              bg=COLORS['card'], fg=COLORS['text'],
                              font=('Microsoft YaHei UI', 12, 'bold'))
        color_label.pack(anchor='w', pady=(0, 8))

        self.bg_color_var = tk.StringVar(value="auto")
        color_frame = tk.Frame(options_section, bg=COLORS['card'])
        color_frame.pack(fill='x', pady=(0, 15))

        colors = [("🤖 自动", "auto"), ("⚪ 白色", "white"), ("⚫ 黑色", "black"), ("🟢 绿色", "green")]
        for text, value in colors:
            tk.Radiobutton(color_frame, text=text, variable=self.bg_color_var,
                          value=value, bg=COLORS['card'], fg=COLORS['text'],
                          font=('Microsoft YaHei UI', 9), selectcolor=COLORS['accent']).pack(anchor='w')

        # 容差设置
        tolerance_label = tk.Label(options_section, text="🎯 颜色容差",
                                  bg=COLORS['card'], fg=COLORS['text'],
                                  font=('Microsoft YaHei UI', 12, 'bold'))
        tolerance_label.pack(anchor='w', pady=(15, 8))

        tolerance_frame = tk.Frame(options_section, bg=COLORS['card'])
        tolerance_frame.pack(fill='x', pady=(0, 15))

        self.tolerance_var = tk.IntVar(value=30)
        self.tolerance_label = tk.Label(tolerance_frame, text="30",
                                       bg=COLORS['card'], fg=COLORS['primary'],
                                       font=('Microsoft YaHei UI', 12, 'bold'))
        self.tolerance_label.pack(side='right')

        tolerance_scale = tk.Scale(tolerance_frame, from_=0, to=100, orient='horizontal',
                                  variable=self.tolerance_var, command=self.update_tolerance_label,
                                  bg=COLORS['card'], fg=COLORS['text'], highlightthickness=0,
                                  troughcolor=COLORS['border'], activebackground=COLORS['primary'])
        tolerance_scale.pack(fill='x', side='left', expand=True, padx=(0, 10))

        # 边框去除选项
        self.border_var = tk.BooleanVar(value=True)
        border_check = tk.Checkbutton(options_section, text="🧹 去除边框",
                                     variable=self.border_var, bg=COLORS['card'],
                                     fg=COLORS['text'], font=('Microsoft YaHei UI', 10),
                                     selectcolor=COLORS['success'])
        border_check.pack(anchor='w', pady=(0, 20))

    def create_center_panel(self, parent):
        """创建中间控制面板"""
        center_panel = tk.Frame(parent, bg=COLORS['card'], relief='flat', bd=0)
        center_panel.pack(side='left', fill='both', padx=(5, 5), ipadx=20)

        # 面板标题
        panel_title = tk.Label(center_panel, text="⚡ 处理控制",
                              bg=COLORS['card'], fg=COLORS['text'],
                              font=('Microsoft YaHei UI', 16, 'bold'))
        panel_title.pack(pady=(20, 30))

        # 处理按钮
        self.process_btn = ModernButton(center_panel, text="✨ 开始魔法处理",
                                      style='primary', command=self.start_processing,
                                      width=20, height=3)
        self.process_btn.pack(pady=(0, 20))

        # 进度显示
        progress_frame = tk.Frame(center_panel, bg=COLORS['card'])
        progress_frame.pack(fill='x', pady=(0, 20))

        self.progress_icon = tk.Label(progress_frame, text="⏳", bg=COLORS['card'],
                                     font=('Arial', 24))
        self.progress_icon.pack(pady=(0, 10))

        self.status_label = tk.Label(progress_frame, text="🔮 等待开始处理...",
                                    bg=COLORS['card'], fg=COLORS['text_light'],
                                    font=('Microsoft YaHei UI', 11), wraplength=200)
        self.status_label.pack()

        # 进度条
        self.progress = ttk.Progressbar(progress_frame, mode='indeterminate', length=200)
        self.progress.pack(pady=(15, 20))

        # 输出按钮
        self.open_folder_btn = ModernButton(center_panel, text="📂 打开结果文件夹",
                                          style='success', command=self.open_output_folder)
        self.open_folder_btn.pack()

    def create_right_panel(self, parent):
        """创建右侧日志面板"""
        right_panel = tk.Frame(parent, bg=COLORS['card'], relief='flat', bd=0)
        right_panel.pack(side='right', fill='both', expand=True, padx=(10, 0))

        # 面板标题
        log_header = tk.Frame(right_panel, bg=COLORS['card'])
        log_header.pack(fill='x', pady=(20, 15))

        panel_title = tk.Label(log_header, text="📋 实时日志",
                              bg=COLORS['card'], fg=COLORS['text'],
                              font=('Microsoft YaHei UI', 16, 'bold'))
        panel_title.pack(side='left')

        clear_btn = ModernButton(log_header, text="🗑️ 清空", style='accent',
                               command=self.clear_log, width=8)
        clear_btn.pack(side='right')

        # 日志文本区域
        log_container = tk.Frame(right_panel, bg=COLORS['card'])
        log_container.pack(fill='both', expand=True, padx=20, pady=(0, 20))

        self.log_text = tk.Text(log_container, height=25, wrap=tk.WORD,
                               font=('Consolas', 9), bg='#1a1a1a', fg='#00ff88',
                               insertbackground='#00ff88', selectbackground='#333333',
                               relief='flat', bd=0)

        log_scrollbar = ttk.Scrollbar(log_container, orient=tk.VERTICAL,
                                     command=self.log_text.yview)
        self.log_text.configure(yscrollcommand=log_scrollbar.set)

        self.log_text.pack(side='left', fill='both', expand=True)
        log_scrollbar.pack(side='right', fill='y')

        # 配置日志颜色
        self.log_text.tag_configure("info", foreground="#00ff88")
        self.log_text.tag_configure("warning", foreground="#ffaa00")
        self.log_text.tag_configure("error", foreground="#ff4444")
        self.log_text.tag_configure("success", foreground="#00ddff")

    def initialize_variables(self):
        """初始化变量"""
        self.selected_path = None
        self.is_folder = False
        self.output_folder = None
        self.processing = False

    def start_animations(self):
        """启动动画效果"""
        self.animate_icons()
        self.animate_title_color()

    def animate_icons(self):
        """动画图标"""
        # 更新标题图标
        current_icon = self.animated_icons['title'].next()
        current_text = self.title_label.cget('text')
        new_text = f"{current_icon} GIF背景去除工具"
        self.title_label.config(text=new_text)

        # 如果正在处理，更新进度图标
        if self.processing:
            process_icon = self.animated_icons['process'].next()
            self.progress_icon.config(text=process_icon)

        self.root.after(2000, self.animate_icons)

    def animate_title_color(self):
        """动画标题颜色渐变"""
        colors = ['#ffffff', '#f0f8ff', '#e6f3ff', '#ffffff']
        current_color = random.choice(colors)
        self.title_label.config(fg=current_color)
        self.root.after(3000, self.animate_title_color)

    def update_tolerance_label(self, value):
        """更新容差标签"""
        self.tolerance_label.config(text=str(int(float(value))))

    def clear_log(self):
        """清空日志"""
        self.log_text.delete(1.0, tk.END)
        self.log_message("🗑️ 日志已清空", "info")

    def log_message(self, message, level="info"):
        """添加日志消息"""
        timestamp = time.strftime("%H:%M:%S")

        emoji_map = {
            "info": "ℹ️",
            "warning": "⚠️",
            "error": "❌",
            "success": "✅"
        }

        emoji = emoji_map.get(level, "📝")
        formatted_message = f"[{timestamp}] {emoji} {message}\n"

        self.log_text.insert(tk.END, formatted_message, level)
        self.log_text.see(tk.END)
        self.root.update()

    def select_single_file(self):
        """选择单个文件"""
        file_path = filedialog.askopenfilename(
            title="🎬 选择GIF文件",
            filetypes=[("GIF files", "*.gif"), ("All files", "*.*")],
            initialdir=os.path.expanduser("~/Desktop")
        )
        if file_path:
            self.selected_path = file_path
            self.is_folder = False
            filename = os.path.basename(file_path)

            # 更新显示
            self.file_status.config(text=f"✅ 已选择: {filename}", fg=COLORS['success'])

            # 高亮按钮
            self.single_file_btn.config(text="✅ 已选择文件", bg=COLORS['success'])
            self.batch_btn.config(text="📁 批量处理文件夹", bg=BUTTON_STYLES['secondary']['bg'])

            self.log_message(f"选择了文件: {filename}", "success")

    def select_folder(self):
        """选择文件夹"""
        folder_path = filedialog.askdirectory(
            title="📁 选择包含GIF文件的文件夹",
            initialdir=os.path.expanduser("~/Desktop")
        )
        if folder_path:
            self.selected_path = folder_path
            self.is_folder = True

            # 统计GIF文件数量
            gif_files = [f for f in os.listdir(folder_path) if f.lower().endswith('.gif')]
            gif_count = len(gif_files)
            folder_name = os.path.basename(folder_path)

            # 更新显示
            self.file_status.config(text=f"✅ 文件夹: {folder_name} ({gif_count}个GIF)",
                                   fg=COLORS['success'])

            # 高亮按钮
            self.batch_btn.config(text="✅ 已选择文件夹", bg=COLORS['success'])
            self.single_file_btn.config(text="📄 选择单个文件", bg=BUTTON_STYLES['primary']['bg'])

            if gif_count > 0:
                self.log_message(f"选择了文件夹: {folder_name} (包含{gif_count}个GIF文件)", "success")
            else:
                self.log_message(f"文件夹中没有找到GIF文件", "warning")

    def get_bg_color(self):
        """获取背景色设置"""
        color_map = {
            'auto': 'auto',
            'white': (255, 255, 255),
            'black': (0, 0, 0),
            'green': (0, 255, 0)
        }
        return color_map.get(self.bg_color_var.get(), 'auto')

    def start_processing(self):
        """开始处理"""
        if not self.selected_path:
            self.show_modern_message("⚠️ 提示", "请先选择文件或文件夹！", "warning")
            return

        # 更新UI状态
        self.processing = True
        self.process_btn.config(text="🔄 处理中...", bg=COLORS['warning'])
        self.progress.start()
        self.status_label.config(text="🚀 启动处理引擎...", fg=COLORS['primary'])

        # 清空之前的日志
        self.log_text.delete(1.0, tk.END)
        self.log_message("🎬 GIF背景去除工具启动", "success")
        self.log_message("⚙️ 正在配置处理参数...", "info")

        # 在新线程中处理
        thread = threading.Thread(target=self.process_files)
        thread.daemon = True
        thread.start()

    def show_modern_message(self, title, message, msg_type="info"):
        """显示现代化消息框"""
        if msg_type == "warning":
            messagebox.showwarning(title, message)
        elif msg_type == "error":
            messagebox.showerror(title, message)
        else:
            messagebox.showinfo(title, message)

    def process_files(self):
        """处理文件"""
        try:
            method = self.method_var.get()
            bg_color = self.get_bg_color()
            tolerance = self.tolerance_var.get()
            remove_border = self.border_var.get()

            # 更新状态
            self.root.after(0, lambda: self.status_label.config(text="⚙️ 配置处理参数..."))

            if self.is_folder:
                # 批量处理
                self.root.after(0, lambda: self.log_message("📁 开始批量处理模式...", "info"))
                self.root.after(0, lambda: self.status_label.config(text="📁 批量处理中..."))

                output_dir = os.path.join(self.selected_path, 'transparent_output')
                self.output_folder = output_dir

                # 重写批量处理以添加更详细的日志
                input_path = Path(self.selected_path)
                if not output_dir:
                    output_path = input_path / 'transparent_output'
                else:
                    output_path = Path(output_dir)
                output_path.mkdir(exist_ok=True)

                gif_files = []
                for ext in self.remover.supported_formats:
                    gif_files.extend(input_path.glob(f'*{ext}'))

                if not gif_files:
                    self.root.after(0, lambda: self.log_message("❌ 未找到GIF文件", "error"))
                    return

                self.root.after(0, lambda: self.log_message(f"📊 找到 {len(gif_files)} 个GIF文件", "info"))

                success_count = 0
                for i, gif_file in enumerate(gif_files):
                    current_file = gif_file.name
                    self.root.after(0, lambda f=current_file: self.log_message(f"🎬 正在处理: {f}", "info"))
                    self.root.after(0, lambda i=i, total=len(gif_files): self.status_label.config(
                        text=f"⚡ 处理进度: {i+1}/{total}"))

                    output_file = output_path / f"transparent_{gif_file.name}"

                    try:
                        if method == 'color':
                            success = self.remover.remove_background_by_color(
                                str(gif_file), str(output_file), bg_color, tolerance, remove_border
                            )
                        else:
                            success = self.remover.remove_background_edge_detection(
                                str(gif_file), str(output_file), remove_border
                            )

                        if success:
                            success_count += 1
                            self.root.after(0, lambda f=current_file: self.log_message(f"✅ 成功处理: {f}", "success"))
                        else:
                            self.root.after(0, lambda f=current_file: self.log_message(f"❌ 处理失败: {f}", "error"))

                    except Exception as e:
                        self.root.after(0, lambda f=current_file, err=str(e): self.log_message(f"💥 处理出错 {f}: {err}", "error"))

                self.root.after(0, lambda: self.log_message(f"🎉 批量处理完成! 成功: {success_count}/{len(gif_files)}", "success"))

            else:
                # 单文件处理
                self.root.after(0, lambda: self.log_message("📄 开始单文件处理模式...", "info"))
                self.root.after(0, lambda: self.status_label.config(text="🎨 单文件处理中..."))

                filename = os.path.basename(self.selected_path)
                output_path = self.selected_path.replace('.gif', '_transparent.gif')
                self.output_folder = os.path.dirname(output_path)

                try:
                    if method == 'color':
                        self.root.after(0, lambda: self.log_message(f"🎨 使用颜色匹配方法处理: {filename}", "info"))
                        success = self.remover.remove_background_by_color(
                            self.selected_path, output_path, bg_color, tolerance, remove_border
                        )
                    else:
                        self.root.after(0, lambda: self.log_message(f"🔍 使用边缘检测方法处理: {filename}", "info"))
                        success = self.remover.remove_background_edge_detection(
                            self.selected_path, output_path, remove_border
                        )

                    if success:
                        self.root.after(0, lambda: self.log_message(f"🎉 文件处理完成: {filename}", "success"))
                    else:
                        self.root.after(0, lambda: self.log_message(f"❌ 文件处理失败: {filename}", "error"))

                except Exception as e:
                    self.root.after(0, lambda err=str(e): self.log_message(f"💥 处理过程中出现错误: {err}", "error"))

        except Exception as e:
            self.root.after(0, lambda err=str(e): self.log_message(f"💥 系统错误: {err}", "error"))
        finally:
            self.root.after(0, self.processing_complete)

    def processing_complete(self):
        """处理完成"""
        self.processing = False
        self.progress.stop()
        self.process_btn.config(text="✨ 开始魔法处理", bg=BUTTON_STYLES['primary']['bg'])
        self.status_label.config(text="🎉 处理完成！", fg=COLORS['success'])
        self.progress_icon.config(text="✅")

        # 播放完成动画
        self.celebration_animation()

        # 显示完成对话框
        result = messagebox.askquestion("🎉 处理完成",
                                       "GIF处理已完成！\n\n🎊 恭喜！要打开结果文件夹查看吗？",
                                       icon='question')
        if result == 'yes':
            self.open_output_folder()

    def celebration_animation(self):
        """庆祝动画"""
        celebration_icons = ["🎉", "🎊", "✨", "🥳", "🎆"]

        def animate_celebration(count=0):
            if count < 10:
                icon = random.choice(celebration_icons)
                self.progress_icon.config(text=icon)
                self.root.after(200, lambda: animate_celebration(count + 1))
            else:
                self.progress_icon.config(text="✅")

        animate_celebration()

    def open_output_folder(self):
        """打开输出文件夹"""
        if self.output_folder and os.path.exists(self.output_folder):
            try:
                if sys.platform == "win32":
                    os.startfile(self.output_folder)
                elif sys.platform == "darwin":
                    os.system(f"open '{self.output_folder}'")
                else:
                    os.system(f"xdg-open '{self.output_folder}'")
                self.log_message(f"📂 已打开输出文件夹", "success")
            except Exception as e:
                self.log_message(f"❌ 无法打开文件夹: {str(e)}", "error")
                self.show_modern_message("❌ 错误", f"无法打开文件夹:\n{str(e)}", "error")
        else:
            self.show_modern_message("⚠️ 提示", "输出文件夹不存在或尚未生成", "warning")

    def run(self):
        """运行应用程序"""
        # 欢迎消息
        self.log_message("🎬 欢迎使用现代化GIF背景去除工具！", "success")
        self.log_message("✨ 选择文件开始你的创作之旅", "info")

        # 启动主循环
        try:
            self.root.mainloop()
        except KeyboardInterrupt:
            self.log_message("👋 用户中断，程序退出", "info")


def main():
    """主函数"""
    print("🎬 GIF背景去除工具 - 极致美化版")
    print("=" * 50)

    parser = argparse.ArgumentParser(
        description='🎬 GIF背景去除工具 - 一键去除GIF图像的背景，使其透明',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
✨ 使用示例:
  python bg.py --gui                    # 启动图形界面 (推荐)
  python bg.py -i input.gif             # 处理单个文件
  python bg.py -i folder/ --batch       # 批量处理文件夹
  python bg.py -i input.gif --bg-color white --tolerance 50

🎨 支持的背景色:
  auto, white, black, green 或 R,G,B格式 (如: 255,255,255)

📧 如有问题请访问: https://github.com/your-repo
        """
    )

    parser.add_argument('--gui', action='store_true',
                       help='🖥️  启动美化图形界面 (推荐使用)')
    parser.add_argument('--input', '-i',
                       help='📁 输入GIF文件或文件夹路径')
    parser.add_argument('--output', '-o',
                       help='💾 输出文件或文件夹路径')
    parser.add_argument('--method', choices=['color', 'edge'], default='color',
                       help='🔧 背景去除方法: color(颜色匹配) 或 edge(边缘检测)')
    parser.add_argument('--bg-color',
                       help='🎨 背景颜色: auto, white, black, green 或 R,G,B格式')
    parser.add_argument('--tolerance', type=int, default=30,
                       help='🎯 颜色容差 (0-100), 默认30')
    parser.add_argument('--batch', action='store_true',
                       help='📦 批量处理模式')
    parser.add_argument('--remove-border', action='store_true', default=True,
                       help='🧹 去除外边框 (默认启用)')
    parser.add_argument('--version', action='version', version='GIF背景去除工具 v2.0 美化版')

    args = parser.parse_args()

    # 如果没有参数或指定了GUI，启动图形界面
    if args.gui or (not args.input and len(sys.argv) == 1):
        print("🚀 启动图形界面...")
        try:
            app = GifBackgroundRemoverGUI()
            app.run()
        except Exception as e:
            print(f"❌ 启动图形界面失败: {str(e)}")
            print("💡 请确保已安装tkinter库")
            sys.exit(1)
        return

    # 命令行模式
    print("⚡ 命令行模式")

    if not args.input:
        print("❌ 错误: 请指定输入文件或文件夹路径")
        print("💡 使用 --help 查看详细帮助")
        return

    if not os.path.exists(args.input):
        print(f"❌ 错误: 输入路径不存在: {args.input}")
        return

    remover = GifBackgroundRemover()

    # 解析背景颜色
    bg_color = 'auto'
    if args.bg_color:
        if args.bg_color.lower() == 'auto':
            bg_color = 'auto'
        elif args.bg_color.lower() == 'white':
            bg_color = (255, 255, 255)
        elif args.bg_color.lower() == 'black':
            bg_color = (0, 0, 0)
        elif args.bg_color.lower() == 'green':
            bg_color = (0, 255, 0)
        elif ',' in args.bg_color:
            try:
                rgb = tuple(map(int, args.bg_color.split(',')))
                if len(rgb) == 3 and all(0 <= c <= 255 for c in rgb):
                    bg_color = rgb
                else:
                    print("❌ 错误: RGB值必须在0-255之间")
                    return
            except ValueError:
                print("❌ 错误: 无效的RGB格式，请使用 R,G,B 格式 (如: 255,255,255)")
                return
        else:
            print(f"❌ 错误: 不支持的背景色: {args.bg_color}")
            print("💡 支持的颜色: auto, white, black, green 或 R,G,B格式")
            return

    # 验证容差值
    if not 0 <= args.tolerance <= 100:
        print("❌ 错误: 容差值必须在0-100之间")
        return

    print(f"⚙️  处理配置:")
    print(f"   📁 输入: {args.input}")
    print(f"   🎨 背景色: {bg_color}")
    print(f"   🎯 容差: {args.tolerance}")
    print(f"   🔧 方法: {args.method}")
    print(f"   🧹 去除边框: {'是' if args.remove_border else '否'}")
    print()

    # 处理文件
    start_time = time.time()

    try:
        if args.batch or os.path.isdir(args.input):
            print("📦 批量处理模式")
            remover.batch_process(args.input, args.output, args.method, bg_color, args.remove_border)
        else:
            print("📄 单文件处理模式")
            if args.method == 'color':
                success = remover.remove_background_by_color(
                    args.input, args.output, bg_color, args.tolerance, args.remove_border
                )
            else:
                success = remover.remove_background_edge_detection(
                    args.input, args.output, args.remove_border
                )

            if success:
                print("✅ 处理完成!")
            else:
                print("❌ 处理失败!")
                sys.exit(1)

        end_time = time.time()
        print(f"\n⏱️  总耗时: {end_time - start_time:.2f} 秒")
        print("🎉 所有处理完成!")

    except KeyboardInterrupt:
        print("\n⚠️  用户中断处理")
        sys.exit(1)
    except Exception as e:
        print(f"\n💥 处理过程中出现错误: {str(e)}")
        sys.exit(1)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n👋 程序被用户中断")
        sys.exit(0)
    except Exception as e:
        print(f"\n💥 程序运行错误: {str(e)}")
        sys.exit(1)
